import { observable, action, computed } from 'mobx';
import objectAssign from 'object-assign';
import { message } from 'antd';
import { hashHistory } from 'react-router';
import { WeaTools } from 'ecCom';
import { getLSValue, setLSValue, initLSValue } from '../util/loginUtil';

import * as LOGIN_API from '../apis/loginApi';

export default class LoginStore {
  // 地址栏参数
  @observable queryParams = {};
  // 升级状态。状态为0时，显示登录页，否则跳转升级页面
  @observable updatestatus = '';
  // 多语言
  @observable multiLangs = getLSValue('login', 'multiLangs') || [];
  // 登陆表单
  // @observable loginFormItems =[];
  // 登录页状态
  @observable state = objectAssign({}, {
    win_width: jQuery(window).width(),
    win_height: jQuery(window).height(),
    isLogging: false,
    hasMultiLang: false,
    multiLangVisible: false,
    loginFormItems: [],
    loginFormHiddenItems: [],
    loginSetting: {},
    validateCode: '/weaver/weaver.file.MakeValidateCode',
  }, objectAssign({}, getLSValue('login', 'loginCache'), {
    loginType: getLSValue('login', 'loginType') || 'form',
    langId: getLSValue('login', 'langId') || '7',
    langText: getLSValue('login', 'langText') || '简体中文',
    isRememberAccount: getLSValue('login', 'isRememberAccount') || false,
    isRememberPassword: getLSValue('login', 'isRememberPassword') || false,
    cacheAccount: getLSValue('login', 'cacheAccount') || '',
    cachePassword: getLSValue('login', 'cachePassword') || '',
    initialSlide: getLSValue('login', 'initialSlide') || 0,
    autoCarousel: getLSValue('login', 'autoCarousel') || false,
    carouselTime: getLSValue('login', 'carouselTime') || 3,
  }));
  // 登录验证码刷新参数
  @observable seriesnum_ = 0;
  // 登录类型  公文交换平台的登录类型为3
  @observable loginType = '3';
  // 公文标题多语言
  @observable labelInfo2 = [];
  // 检验是否有权限
  @observable haslisence = true;
  constructor() {
    this.setState = this.setState.bind(this);
    this.setStateAndCache = this.setStateAndCache.bind(this);
    this.getMultiLangs = this.getMultiLangs.bind(this);
    this.getUpgradeInfo = this.getUpgradeInfo.bind(this);
    this.getLoginInfo = this.getLoginInfo.bind(this);
    this.getLoginForm = this.getLoginForm.bind(this);
    this.onRememberChange = this.onRememberChange.bind(this);
    this.onValidateCodeChange = this.onValidateCodeChange.bind(this);
    this.getOdocExchangeLoginSetting = this.getOdocExchangeLoginSetting.bind(this);
  }

  @computed
  get labelObj() {
    const { langId, labelInfo } = this.state;
    return labelInfo[`langid${langId}`] || {};
  }

  @computed
  get labelObj2() {
    const { langId } = this.state;
    return this.labelInfo2[`langid${langId}`] || {};
  }

  @action
  setState(state) {
    this.state = objectAssign({}, this.state, state);
  }

  @action
  setStateAndCache(key, value) {
    this.setState({ [key]: value });
    setLSValue('login', key, value);
  }

  @action
  getMultiLangs(params = {}) {
    LOGIN_API.getActiveLanguage(params).then((result) => {
      if (result.status == '1') {
        const { activeLanguageInfo, activeLanguageIds, languageIdentify } = result;
        this.multiLangs = activeLanguageInfo;
        setLSValue('login', 'multiLangs', activeLanguageInfo);
        WeaTools.ls.set('activeLanguageIds', activeLanguageIds);
        WeaTools.ls.set('languageIdentify', languageIdentify);
      }
    });
  }

  @action
  getUpgradeInfo(params = {}) {
    LOGIN_API.getUpgradeInfo(params).then((result) => {
      const { updatestatus, upgradeurl } = result;
      this.updatestatus = updatestatus;
      if (updatestatus == '0') {
        this.getLoginInfo(params);
      } else {
        window.location.href = upgradeurl;
      }
    });
  }

  @action
  getLoginInfo(params = {}) {
    this.queryParams = params;
    this.updatestatus = '0';
    LOGIN_API.getLoginInfo(params).then((result) => {
      // 缓存登录日期
      const date = new Date();
      const logindate = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
      WeaTools.ls.set('logindate', logindate);

      if (result.status != '2') {
        const { loginTemplateTitle = '', loginSettingInfo = {}, bgImagesInfo = [], settingversion } = result;
        const { loginInfo = {} } = loginSettingInfo;

        // 设置浏览器窗口标题
        document.title = loginTemplateTitle;

        // 获取幻灯片默认位置
        const _loginBgImage = getLSValue('login', 'loginBgImage');
        let initialSlide = 0;
        const loginBgImage = _loginBgImage || loginInfo.imgsrc;
        for (let i = 0, len = bgImagesInfo.length; i < len; i++) {
          if (bgImagesInfo[i].imgsrc == loginBgImage) {
            initialSlide = i;
            break;
          }
        }
        setLSValue('login', 'initialSlide', initialSlide);
        // 获取幻灯片是否自动轮播
        const _autoCarousel = getLSValue('login', 'autoCarousel');
        const autoCarousel = _autoCarousel != undefined ? _autoCarousel : loginInfo.autoCarousel;
        setLSValue('login', 'autoCarousel', autoCarousel);
        // 获取幻灯片自动轮播间隔时间
        const _carouselTime = getLSValue('login', 'carouselTime');
        const carouselTime = _carouselTime || loginInfo.carouselTime;
        setLSValue('login', 'carouselTime', carouselTime);

        const state = objectAssign({}, result, { initialSlide, autoCarousel, carouselTime });
        setLSValue('login', 'loginCache', state);

        // 判断设置版本和缓存版本是否一致，不一致则需要刷新
        const _settingversion = getLSValue('login', 'settingversion');
        if (settingversion != _settingversion) {
          this.setState(state);
          setLSValue('login', 'settingversion', settingversion);
        }
      } else {
        message.error(result.errormsg);
      }
    });
  }

  @action
  getOdocExchangeLoginSetting() {
    LOGIN_API.getOdocExchangeLoginSetting().then((result) => {
      this.labelInfo2 = result.labelInfo;
    });
  }

  @action
  getLoginForm(params = {}) {
    const { logintype = this.loginType } = this.queryParams;
    const { loginId = '', langId = this.state.langId } = params;

    window.doLoginAction && window.doLoginAction('getLoginForm', {
      logintype,
      loginid: loginId,
      langid: langId,
      callback: (result) => {
        const { hasMultiLang = false, loginFormItems = [], loginFormHiddenItems = [], loginSetting = {} } = result;
        /* loginFormItems.push({
            atype:"common",id:"tokenAuthKey",label:"请输入动态令牌口令",name:"tokenAuthKey",type:"text"
        }); */
        this.setState({ hasMultiLang, loginFormItems, loginFormHiddenItems, loginSetting });
      },
    });

    /* LOGIN_API.getLoginForm({ logintype: logintype, loginid: loginId, langid: langId}).then(result=>{
        const {hasMultiLang = false, formItems = [], loginFormHiddenItems = [], loginSetting = {}} = result;
        formItems.push({
            atype:"common",id:"tokenAuthKey",label:"请输入动态令牌口令",name:"tokenAuthKey",type:"text"
        });
        this.setState({hasMultiLang:true, loginFormItems:formItems, loginFormHiddenItems, loginSetting});
    }); */
  }

  /* login(){
      const loginid = jQuery('#loginid').val();
      let userpassword = jQuery('#userpassword').val();
      const tokenAuthKey = jQuery('#tokenAuthKey') ? jQuery('#tokenAuthKey').val() : '';
      const validatecode = jQuery('#validatecode') ? jQuery('#validatecode').val() : '';
      const messages = jQuery('#messages') ? jQuery('#messages').val() : '';
      if (loginid == '' || userpassword == '') {
          message.error(getLabel('386478',"请输入用户名、密码"), 3);
         // if (failure && typeof failure == 'function') failure();
          return;
      }

      LOGIN_API.login({
          islanguid: 7,
          loginid: loginid,
          userpassword: userpassword,
          tokenAuthKey: tokenAuthKey,
          validatecode: validatecode,
          logintype: 1,
          messages: messages
      }).then(data=>{
          if(data.loginstatus=="true"){
              hashHistory.push("/main/odocExchange/test");
          }else{
              message.error(data.msg, 3);
          }
      });
  } */

  @action
  onValidateCodeChange() {
    setTimeout(() => this.setState({ validateCode: `/weaver/weaver.file.MakeValidateCode?seriesnum_=${++this.seriesnum_}` }), 50);
  }

  @action
  onLogin() {
    const { logintype = this.loginType } = this.queryParams;
    const { langId, langText, isRememberAccount, isRememberPassword, loginSetting } = this.state;

    this.setState({ isLogging: true });
    window.doLoginAction && window.doLoginAction('login', {
      logintype,
      langid: langId,
      loginSetting,
      success: (username, password) => {
        jQuery.setSessionTimeZone && jQuery.setSessionTimeZone();

        let cacheAccount = '';
        let cachePassword = '';
        if (isRememberAccount) cacheAccount = username;
        if (isRememberPassword) cachePassword = password;
        this.setState({ isRememberAccount, isRememberPassword, cacheAccount, cachePassword });

        setLSValue('login', 'langId', langId);
        setLSValue('login', 'langText', langText);
        setLSValue('login', 'cacheAccount', cacheAccount);
        setLSValue('login', 'cachePassword', cachePassword);
        setLSValue('login', 'isRememberAccount', isRememberAccount);
        setLSValue('login', 'isRememberPassword', isRememberPassword);

        initLSValue(username, langId);
        WeaTools.ls.set('languageidweaver', langId);

        if (logintype == '2') {
          window.location.href = '/spa/crmPortal/mobx/index.html#/main';
        } else {
          // 判断当前登录日期和上次登录的日期是否为同一天，不是同一天则刷新页面
          const date = new Date();
          const logindate = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
          const _logindate = WeaTools.ls.getStr('logindate');
          if (logindate != _logindate) {
            WeaTools.ls.set('logindate', logindate);
            window.location.href = '/wui/index2.html?#/main';
          } else {
            // weaHistory.push({pathname: getDefaultPathname()});
            // hashHistory.push("/main/odocExchange/Nav");
            this.toIndex();
          }
        }
        this.setState({ isLogging: false });
      },
      failure: (params = {}) => {
        if (params.reflashValidateCode) {
          this.onValidateCodeChange();
        }
        this.getLoginForm();
        this.setState({ isLogging: false });
      },
    });
  }


  @action
  onRememberChange(type, checked) {
    const { isRememberAccount, isRememberPassword } = this.state;
    if (type == 'account') {
      this.setState({
        isRememberAccount: checked,
        isRememberPassword: !checked ? checked : isRememberPassword,
      });
    } else if (type == 'password') {
      this.setState({
        isRememberAccount: checked || isRememberAccount,
        isRememberPassword: checked,
      });
    }
  }
  @action checkInfo() {
    LOGIN_API.checkInfo().then((data) => {
      this.haslisence = data.api_status;
    });
  }

  toIndex() {
    LOGIN_API.getMenus().then((result) => {
      // 获取当前用户菜单，并将菜单缓存到本地浏览器  每次登陆时强制刷新
      let menus = result.menus;
      WeaTools.ls.set('odoc_exchange_menus', menus);
      // 默认跳转到第一个菜单
      let indexMenuId = menus[0].id;
      hashHistory.push(`/main/odocExchange/Nav/${indexMenuId}`);
    });
  }
}
